import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:get/get.dart' hide FormData, MultipartFile, Response;
import 'package:study_demo/api/api.dart';

import '../../../base/BaseController.dart';

class UploadMusicController extends BaseController {
  final result = ''.obs;
  final filePath = ''.obs;

  chooseFile() async {
    final result = await FilePicker.platform.pickFiles();
    if (result != null) {
      final path = result.files.single.path;
      filePath.value = path!;
    }
  }

  uploadMusic() async {
    // 3. 创建 Dio 实例
    Dio dio = Dio();
    dio.options.followRedirects = true;
    dio.options.maxRedirects = 5;

// 添加请求头
    dio.options.headers = {
      'Accept': 'application/json',
      'Content-Type': 'multipart/form-data',
    };

// 4. 构造 FormData
    FormData formData = FormData.fromMap({
      "file":
          await MultipartFile.fromFile(filePath.value, filename: 'test.mp3'),
      // 添加其他可能需要的参数
      "timestamp": DateTime.now().millisecondsSinceEpoch.toString(),
    });

    var uploadUrl = 'http://113.45.190.183:8102/upload/';
    print(uploadUrl);

    try {
      // 5. 发送 POST 请求到服务器
      Response response = await dio.post(
        uploadUrl,
        data: formData,
        onSendProgress: (int sent, int total) {
          print('上传进度: ${(sent / total * 100).toStringAsFixed(0)}%');
        },
      );

      print("上传成功: ${response.data}");
    } on DioException catch (e) {
      print("上传失败: ${e.message}");
      if (e.response != null) {
        print("状态码: ${e.response!.statusCode}");
        print("响应数据: ${e.response!.data}");
        print("响应头: ${e.response!.headers}");
      }
    } catch (e) {
      print("其他错误: $e");
    }
  }
}
